//
//  XGUserDetailTopView.swift
//  TodayNews
//
//  Created by monkey on 2020/2/12.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import Kingfisher
import MBProgressHUD

protocol XGUserDetailHeaderViewDelegate: AnyObject
{
    func userDetailHeaderViewFoldRecommendUser(isFold: Bool) -> Void
    func goBackButtonClick() -> Void
}

/// 推荐视图高度
private let KRecommendRelationViewHeight: CGFloat = 240

class XGUserDetailHeaderView: UIView
{
    /// 代理
    weak var delegate: XGUserDetailHeaderViewDelegate?
    /// 头部视图高度
    private(set) var headerViewHeight: CGFloat = 0.0
    
    /// 用户详情视图模型
    var userDetailViewModel: XGUserDetailViewModel? {
        didSet {
            guard let viewModel =  userDetailViewModel else {
                return
            }
            
            recommendUserView.userDetailViewModel = viewModel
            if let avatarUrl = viewModel.avatar_url {
                userIconImageView.kf.setImage(with: URL(string: avatarUrl))
            }
            verifyImageView.isHidden = !viewModel.isUserVerified
            userNameLabel.text = viewModel.userName
            descriptionLabel.text = viewModel.userDescription
            followingsLabel.text = viewModel.followingsCountStr
            fansLabel.text = viewModel.followersCountStr
            followingButton.isHidden = false
            followingButton.isSelected = viewModel.isFollowing
            
            let verifyLabelOffset: CGFloat = viewModel.isUserVerified ? 10 : 0
            verifyLabel.text = viewModel.verifiedContent
            verifyLabel.isHidden = !viewModel.isUserVerified
            verifyLabel.snp.updateConstraints { (make) in
                make.top.equalTo(userNameLabel.snp.bottom).offset(verifyLabelOffset)
            }
            
            areaLabel.text = viewModel.area
            areaLabel.isHidden = viewModel.area == nil
            let areaLabelOffset: CGFloat = viewModel.area != nil ? 10 : 0
            areaLabel.snp.updateConstraints { (make) in
                make.top.equalTo(verifyLabel.snp.bottom).offset(areaLabelOffset)
            }
            
            layoutIfNeeded()
            headerViewHeight = ceil(fansLabel.frame.maxY) + 10
        }
    }
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 私有属性
    
    /// 用户头像
    private lazy var userIconImageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
    /// 认证标志
    private lazy var verifyImageView: UIImageView = UIImageView(image: UIImage(named: "all_v_avatar_18x18_"))
    /// 用户名
    private lazy var userNameLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 25, textAlignment: .left)
    /// 认证内容
    private lazy var verifyLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 15, textAlignment: .left)
    /// 位置
    private lazy var areaLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 15, textAlignment: .left)
    /// 描述
    private lazy var descriptionLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 15, textAlignment: .left)
    /// 关注
    private lazy var followingsLabel: UILabel = UILabel(text: "测试", textColor: UIColor.orange, fontSize: 20, textAlignment: .left)
    /// 粉丝数
    private lazy var fansLabel: UILabel = UILabel(text: "测试", textColor: UIColor.orange, fontSize: 20, textAlignment: .left)
    /// 推荐关注按钮
    private lazy var recommendButton: UIButton = { [weak self] in
        let button = UIButton(imageName: "arrow_up_16_16x14_", target: self, action: #selector(foldRecommendUserAction(button:)))
        button.layer.borderColor = UIColor(white: 0.9, alpha: 1).cgColor
        button.layer.borderWidth = 1
        return button
    }()
    /// 加载按钮
    private lazy var loadingButton: UIButton = {
        let button = UIButton(imageName: "loading_12x12_", target: self, action: #selector(foldRecommendUserAction(button:)))
        button.layer.borderColor = UIColor(white: 0.9, alpha: 1).cgColor
        button.layer.borderWidth = 1
        button.isHidden = true
        return button
    }()
    /// 关注按钮
    private lazy var followingButton: UIButton = {
        let button = UIButton(title: "关注", selectedTitle: "已关注", fontSize: 15, normalColor: UIColor.white, target: self, action: #selector(followOrUnfollowRelationAction(button:)))
        button.setTitleColor(UIColor.lightGray, for: .selected)
        button.setBackgroundImage(UIColor(r: 227, g: 90, b: 86).toImage(), for: .normal)
        button.setBackgroundImage(UIColor.white.toImage(), for: .selected)
        button.layer.borderColor = UIColor(white: 0.9, alpha: 1).cgColor
        button.layer.borderWidth = 1
        button.isHidden = true
        return button
    }()
    /// 推荐关注用户视图
    private lazy var recommendUserView: XGRecommendUserView = XGRecommendUserView()
}

// MARK: - 私有扩展

private extension XGUserDetailHeaderView
{
    /// 关注/取消关注用户
    @objc func followOrUnfollowRelationAction(button: UIButton) -> Void
    {
        userDetailViewModel?.isFollowRelationChanged = true
        let userId = userDetailViewModel?.userId ?? 0
        if button.isSelected { // 当前选中状态 取消关注用户
            userDetailViewModel?.unfollowRelation(userId: userId, completionHandle: { (isSuccess) in
                if isSuccess {
                    button.isSelected = !button.isSelected
                } else {
                    MBProgressHUD.showErrorTips(text: "取消关注失败,当前网络不佳或今日操作次数已满!")
                }
            })
        } else { // 当前非选中状态 关注用户
            userDetailViewModel?.followRelation(userId: userId, completionHandle: { (isSuccess) in
                if isSuccess {
                    button.isSelected = !button.isSelected
                }
            })
        }
    }
    
    /// 展开/折叠 推荐用户视图
    @objc func foldRecommendUserAction(button: UIButton) -> Void
    {
        guard let viewModel = userDetailViewModel else {
            return
        }
         
        button.isSelected = !button.isSelected
        if button.isSelected {  // button选中 加载阶段
            loadingButton.isHidden = false
            button.isHidden = true
            let animation = CABasicAnimation(keyPath: "transform.rotation")
            animation.toValue = Double.pi * 2
            animation.duration = 0.5
            animation.repeatCount = MAXFLOAT
            loadingButton.imageView?.layer.add(animation, forKey: "transform.rotation")
            // 加载用户推荐数据
            viewModel.fetchUserRecommendRelation(userId: viewModel.userId) { (isSuccess) in
                self.loadingButton.imageView?.layer.removeAllAnimations()
                self.loadingButton.isHidden = true
                button.isHidden = false
                if isSuccess {
                    self.headerViewHeight += KRecommendRelationViewHeight
                    // 代理方法传递给控制器
                    self.delegate?.userDetailHeaderViewFoldRecommendUser(isFold: false)
                    // 更新推荐视图高度约束
                    self.recommendUserView.isHidden = false
                    self.recommendUserView.snp.updateConstraints { (make) in
                        make.height.equalTo(KRecommendRelationViewHeight)
                    }
                    UIView.animate(withDuration: 0.25, animations: {
                        button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                        self.layoutIfNeeded()
                    }) { (_) in
                        self.recommendUserView.userCards = viewModel.recommendUserCards
                    }
                }
            }
        } else { // button非选中 折叠回去
            self.headerViewHeight -= KRecommendRelationViewHeight
            delegate?.userDetailHeaderViewFoldRecommendUser(isFold: true)
            recommendUserView.snp.updateConstraints { (make) in
                make.height.equalTo(0)
            }
            UIView.animate(withDuration: 0.25, animations: {
                button.imageView?.transform = CGAffineTransform(rotationAngle: 0.0001)
                self.layoutIfNeeded()
            }) { (_) in
                self.recommendUserView.userCards = nil
                self.recommendUserView.isHidden = true
            }
        }
    }
    
    /// 返回事件
    @objc func goBackAction() -> Void
    {
        delegate?.goBackButtonClick()
    }
    
    /// 设置界面
    func setUpUI() -> Void
    {
        backgroundColor = UIColor.white
        
        // 背景
        let bgImageView = UIImageView(image: UIImage(named: "wallpaper_profile_night"))
        let goBackButton = UIButton(imageName: "personal_home_back_white_24x24_", target: self, action: #selector(goBackAction))
        addSubview(bgImageView)
        addSubview(goBackButton)
        bgImageView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(150)
        }
        goBackButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(TodayNews_StatusBar_Height)
        }
            
        // 容器1
        let containerView1 = UIView()
        containerView1.backgroundColor = UIColor.white
        containerView1.addSubview(recommendButton)
        recommendButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        containerView1.addSubview(loadingButton)
        loadingButton.snp.makeConstraints { (make) in
            make.center.size.equalTo(recommendButton)
        }
        containerView1.addSubview(followingButton)
        followingButton.snp.makeConstraints { (make) in
            make.right.equalTo(recommendButton.snp.left).offset(-10)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        addSubview(containerView1)
        containerView1.snp.makeConstraints { (make) in
            make.top.equalTo(bgImageView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        // 推荐视图
        recommendUserView.isHidden = true
        addSubview(recommendUserView)
        recommendUserView.snp.makeConstraints { (make) in
            make.top.equalTo(containerView1.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        
        addSubview(userIconImageView)
        userIconImageView.layer.cornerRadius = 40
        userIconImageView.layer.masksToBounds = true
        userIconImageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(bgImageView.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.size.equalTo(CGSize(width: 80, height: 80))
        }
        
        addSubview(verifyImageView)
        verifyImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(userIconImageView.snp.right).offset(-10)
            make.centerY.equalTo(userIconImageView.snp.bottom).offset(-10)
        }
        
        addSubview(userNameLabel)
        userNameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(recommendUserView.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
        }
        
        let flagImageView = UIImageView(image: UIImage(named: "toutiaohao_34x14_"))
        addSubview(flagImageView)
        flagImageView.snp.makeConstraints { (make) in
            make.left.equalTo(userNameLabel.snp.right).offset(10)
            make.centerY.equalTo(userNameLabel)
        }
        
        addSubview(verifyLabel)
        verifyLabel.snp.makeConstraints { (make) in
            make.top.equalTo(userNameLabel.snp.bottom).offset(10)
            make.left.equalTo(userNameLabel)
            make.width.equalTo(TodayNews_Screen_Width - 20)
        }
            
        addSubview(areaLabel)
        areaLabel.snp.makeConstraints { (make) in
            make.top.equalTo(verifyLabel.snp.bottom).offset(10)
            make.left.equalTo(userNameLabel)
            make.width.equalTo(verifyLabel)
        }
        
        addSubview(descriptionLabel)
        descriptionLabel.snp.makeConstraints { (make) in
            make.top.equalTo(areaLabel.snp.bottom).offset(10)
            make.left.equalTo(userNameLabel)
            make.width.equalTo(verifyLabel)
        }
        
        addSubview(followingsLabel)
        followingsLabel.snp.makeConstraints { (make) in
            make.top.equalTo(descriptionLabel.snp.bottom).offset(10)
            make.left.equalTo(userNameLabel)
        }
        
        addSubview(fansLabel)
        fansLabel.snp.makeConstraints { (make) in
            make.left.equalTo(followingsLabel.snp.right).offset(20)
            make.centerY.equalTo(followingsLabel)
        }
        
        let lineView = UIView()
        lineView.backgroundColor = UIColor(white: 0.9, alpha: 1)
        addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.left.bottom.width.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        layoutIfNeeded()
        headerViewHeight = ceil(fansLabel.frame.maxY) + 10
    }
}
